package net.ywd.xp1024search.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;

/**
 * @Author Dreamingodd
 * @Date 2017/04/19
 *
 * Change to POST method.
 * @Author Dreamingodd
 * @Date 2018/07/18
 */
public class WebContentUtil {

    private static Logger logger = LoggerFactory.getLogger(WebContentUtil.class);

    public static String readWebContent(String urlStr, String env) {
        try {
            HttpURLConnection httpcon = null;
            URL url = new URL(urlStr);
            if ("local".equalsIgnoreCase(env)) {
                System.setProperty("http.proxyHost", "127.0.0.1");
                System.setProperty("http.proxyPort", "49440");
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 49440));
                httpcon = (HttpURLConnection) url.openConnection(proxy);
            } else {
                httpcon = (HttpURLConnection) url.openConnection();
            }
            httpcon.addRequestProperty("User-Agent", "Mozilla/4.76");
            httpcon.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream(), "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception e) {
            logger.error(urlStr + " read failed.", e);
        }
        return "";
    }
}
